/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.util.ArrayList;
import java.util.List;
import javabeans.GroupPlan;
import org.hibernate.HibernateException;
import org.hibernate.Query;

/**
 *
 * @author liweijiao
 */
public class IGroupPlanImpl extends DAO implements IGroupPlan {

    public GroupPlan newGroupPlan(GroupPlan gplan) {
        try {
            begin();
            this.getSession().save(gplan);
            commit();
            return gplan;
        } catch (HibernateException e) {
            rollback();
            return null;

        }

    }

    public boolean updateGroupPlan(GroupPlan gplan) {
        try {
            begin();
            this.getSession().saveOrUpdate(gplan);
            commit();
            return true;
        } catch (HibernateException e) {
            e.printStackTrace();
            rollback();
            return false;

        }
    }

    public boolean deleteGroupPlan(GroupPlan gplan) {
        try {
            begin();
            this.getSession().delete(gplan);

            commit();
            return true;
        } catch (HibernateException e) {
            e.printStackTrace();
            rollback();
            return false;

        }
    }

    public GroupPlan getGroupPlan(int gplanid) {
        try {
            System.out.println("groupplan selecting");
            begin();
            Query q = getSession().createQuery("from GroupPlan gp where gp.groupplanid= :gpid");
            q.setInteger("gpid", gplanid);
            commit();
            GroupPlan gp = (GroupPlan) q.uniqueResult();
            return gp;
        } catch (HibernateException e) {
            e.printStackTrace();
            rollback();
            return null;

        }
    }

    public List<GroupPlan> getGroupPlanbyUserId(int userid) {
        try {


            begin();
            Query q = getSession().createQuery("select gp from GroupPlan gp join gp.groupmembers m where m.id= :uid ");
            q.setInteger("uid", userid);
            commit();
            List resultlist = q.list();
            System.out.println(resultlist.size());
            List<GroupPlan> list = (List<GroupPlan>) resultlist;

            return list;


        } catch (HibernateException e) {
            e.printStackTrace();
            rollback();
            return null;

        }
    }

    public List<GroupPlan> viewAllGroupPlan() {
        try {


            begin();
            Query q = getSession().createQuery("from GroupPlan gp");
            commit();
            List resultlist = q.list();
            List<GroupPlan> list = (List<GroupPlan>) resultlist;
            return list;


        } catch (HibernateException e) {
            e.printStackTrace();
            rollback();
            return null;

        }
    }
}
